package com.test.springboot.springBootUtils.aop;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.alibaba.fastjson.JSON;
import com.test.springboot.springBootUtils.jpa.bean.ExceptionLog;
import com.test.springboot.springBootUtils.jpa.bean.OperationLog;
import com.test.springboot.springBootUtils.service.ExceptionLogService;
import com.test.springboot.springBootUtils.service.OperationLogService;
import com.test.springboot.springBootUtils.util.UserShiroUtil;

/**
 * 切面处理类，操作日志异常日志记录处理
 *
 * @author huyong
 */
@Aspect
@Component
public class OperLogAspect {
    /**
     * 操作版本号
     * <p>
     * 项目启动时从命令行传入，例如: java -jar xxx.war --version=202010
     * </p>
     */
    @Value("${version}")
    private String operVer;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private ExceptionLogService exceptionLogService;

    /**
     * 设置操作日志切入点，记录操作日志 在注解的位置切入代码
     */
    // @Pointcut("@annotation(com.hyd.zcar.cms.common.utils.annotation.OperLog)")
    @Pointcut("@annotation(com.test.springboot.springBootUtils.aop.OperLog)")
    public void operLogPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志，扫描所有controller 包下操作
     */
    //@Pointcut("execution(* com.hyd.zcar.cms.controller..*.*(..))")
    @Pointcut("execution(* com.test.springboot.springBootUtils.jpa.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接正常执行完成后执行，如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        //获取 RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从RequestAttributes 中获取HttpServletRequest 信息
        HttpServletRequest httpServletRequest = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        OperationLog operationLog = new OperationLog();
        try {
            //从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            //获取操作
            OperLog operLog = method.getAnnotation(OperLog.class);
            if (Objects.nonNull(operLog)) {
                String operModul = operLog.operModul();

                String operType = operLog.operType();

                String operDesc = operLog.operDesc();

                operationLog.setOperDesc(operDesc);
                operationLog.setOperModul(operModul);
                operationLog.setOperType(operType);
            }
            //获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            //获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            operationLog.setOperMethod(methodName);
            //获取请求参数
            Map<String, String> rtnMap = converMap(httpServletRequest.getParameterMap());
            operationLog.setOperRequParam(JSON.toJSONString(rtnMap));
            operationLog.setOperRespParam(JSON.toJSONString(keys));
            operationLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName());
            operationLog.setOperUserName(UserShiroUtil.getCurrentUserName());
            operationLog.setOperUri(httpServletRequest.getRequestURI());
            operationLog.setOperCreateTime(new Date());
            operationLog.setOperVer(operVer);
            operationLogService.insert(operationLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        ExceptionLog excepLog = new ExceptionLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            excepLog.setExcRequParam(params); // 请求参数
            excepLog.setOperMethod(methodName); // 请求方法名
            excepLog.setExcName(e.getClass().getName()); // 异常名称
            excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
            excepLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作员ID
            excepLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作员名称
            excepLog.setOperUri(request.getRequestURI()); // 操作URI
          //  excepLog.setOperIp(IPUtil.getRemortIP(request)); // 操作员IP
            excepLog.setOperVer(operVer); // 操作版本号
            excepLog.setOperCreateTime(new Date()); // 发生异常时间
            exceptionLogService.insert(excepLog);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }

    private Map<String, String> converMap(Map<String, String[]> parameterMap) {
        HashMap<String, String> map = new HashMap<>();

        for (String key : parameterMap.keySet()) {
            map.put(key, parameterMap.get(key)[0]);
        }
        return map;
    }

    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer buffer = new StringBuffer();
        for (StackTraceElement stet : elements) {
            buffer.append(stet + "\n");
        }
        String message = exceptionMessage + ":" + exceptionMessage + "\n\t" + buffer.toString();
        return message;
    }
}
